document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    const rememberMeCheckbox = document.getElementById('rememberMe');
    const loginButton = loginForm.querySelector('.login-btn');
    const messageBox = document.querySelector('.message-box');
    const messageText = messageBox.querySelector('span');
    
    // 检查是否有保存的邮箱
    const savedEmail = localStorage.getItem('rememberedEmail');
    if (savedEmail) {
        emailInput.value = savedEmail;
        rememberMeCheckbox.checked = true;
    }

    // 密码显示切换
    document.querySelector('.toggle-password').addEventListener('click', function() {
        const type = passwordInput.type === 'password' ? 'text' : 'password';
        passwordInput.type = type;
        this.querySelector('i').classList.toggle('fa-eye');
        this.querySelector('i').classList.toggle('fa-eye-slash');
    });

    // 表单验证函数
    function validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }

    function validatePassword(password) {
        return password.length >= 6;
    }

    function showError(input, message) {
        const errorText = input.parentElement.querySelector('.error-text');
        errorText.textContent = message;
        errorText.style.display = 'block';
        input.style.borderBottomColor = '#c62828';
    }

    function clearError(input) {
        const errorText = input.parentElement.querySelector('.error-text');
        errorText.style.display = 'none';
        input.style.borderBottomColor = '';
    }

    function showMessage(message, isError = true) {
        messageBox.style.display = 'flex';
        messageText.textContent = message;
        messageBox.className = `message-box ${isError ? 'error' : 'success'}`;
    }

    function setLoading(isLoading) {
        const spinner = loginButton.querySelector('.spinner');
        const buttonText = loginButton.querySelector('span');
        loginButton.disabled = isLoading;
        spinner.style.display = isLoading ? 'block' : 'none';
        buttonText.style.opacity = isLoading ? '0' : '1';
    }

    // 输入事件监听
    emailInput.addEventListener('input', () => clearError(emailInput));
    passwordInput.addEventListener('input', () => clearError(passwordInput));

    // 表单提交处理
    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const email = emailInput.value.trim();
        const password = passwordInput.value.trim();
        let hasError = false;

        // 清除之前的错误
        clearError(emailInput);
        clearError(passwordInput);
        messageBox.style.display = 'none';

        // 验证邮箱
        if (!email) {
            showError(emailInput, '请输入邮箱地址');
            hasError = true;
        } else if (!validateEmail(email)) {
            showError(emailInput, '请输入有效的邮箱地址');
            hasError = true;
        }

        // 验证密码
        if (!password) {
            showError(passwordInput, '请输入密码');
            hasError = true;
        } else if (!validatePassword(password)) {
            showError(passwordInput, '密码至少需要6个字符');
            hasError = true;
        }

        if (hasError) return;

        // 开始登录流程
        setLoading(true);

        try {
            const response = await fetch('/api/users/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ email, password })
            });

            const data = await response.json();

            if (data.success) {
                // 处理"记住我"
                if (rememberMeCheckbox.checked) {
                    localStorage.setItem('rememberedEmail', email);
                } else {
                    localStorage.removeItem('rememberedEmail');
                }

                // 保存token
                localStorage.setItem('token', data.token);
                
                // 显示成功消息
                showMessage('登录成功，正在跳转...', false);
                
                // 延迟跳转到首页
                setTimeout(() => {
                    window.location.href = '/';
                }, 1500);
            } else {
                showMessage(data.message || '登录失败，请检查邮箱和密码');
            }
        } catch (error) {
            console.error('登录错误:', error);
            showMessage('登录失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    });

    // 忘记密码链接处理
    document.getElementById('forgotPassword').addEventListener('click', function(e) {
        e.preventDefault();
        // TODO: 实现忘记密码功能
        alert('忘记密码功能即将上线');
    });
});
